<?php

namespace app\common\model\company;
use app\common\model\user\User;
use think\facade\Session;
use app\api\controller\Pub;
use app\common\model\customer\Customer;
use app\common\model\customer\Street;
use app\common\model\power\Rolepower;
use think\Model;
class Company extends Model
{
     // 设置当前模型对应的完整数据表名称
        protected $table = 'company';
        protected $pk = 'CompanyId';
        
        const STATEINT    = 1;//初始化
        const STATEOK     = 1;//没问题的
        const STATEDELETE = 3;//被删除的订单
    public function continfo(){
        return $this->hasMany('app\common\model\company\Contract','CompanyId','CompanyId');
    }
    public function orderinfo(){
        return $this->hasMany('app\common\model\orderhawa\HawaList','CompanyId','CompanyId');
    }
    public function bussinfo()
    {
        return $this->hasOne('app\common\model\user\User', 'UserId', 'BussinessId');
    }
    /**
     * 状态分类
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public static function getStatusText($value = '')
    {
        $status = [-1=>'全部企业',1=>'正常企业',2=>'锁定企业'];
        if($value!==''){
            return $status[$value];
        }
        return $status;
    }
    
    /**
     * 创建企业信息
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function user_create($data,$type='hawa'){
        $userlogininfo = Pub::getuserid();
        $userid = $userlogininfo['msg'];
        $company = new Company();
        if($type=='hawa'){
            $company->UserId = $userid;
        }else if($type=='buss'){
            $company->BussinessId = $userid;
        }
        if(!empty($data['username'])){
            $company->UserName = $data['username'];
            $company->UserTel = $data['tel'];
        }
        if(!empty($data['usertel'])){
            $company->UserTel = $data['usertel'];
        }
        $company->Name = $data['name'];
        $company->Tel = $data['tel'];
        if(!empty($data['license'])){
           $company->License = $data['license'];
        }
        
        if(!empty($data['img'])){
           $company->Img = $data['img'];
        }

        //街道id
        if(!empty($data['StreetId'])){
           $company->StreetId = $data['StreetId'];
        }

        $company->Lon = $data['lon'];
        $company->Lat = $data['lat'];
        $company->Address = $data['address'];
        if(!empty($data['isplanform'])){
           $company->IsPlanform = $data['isplanform'];
        }
        $company->State = Company::STATEINT;
        $company->CreateTime = date('Y-m-d H:i',time());
        if(!empty($data['LicenseNumber'])){
            $company->LicenseNumber = $data['LicenseNumber'];
        }
        $company->save();
        return $company->CompanyId;
    }

    
     /**
     * 身份证字段默认隐藏
     * @param  [type] $value [description]
     * @return [type]        [description]
     */
     public static function getUserCardAttr($value)
    {   
        if(!empty($value)){
            return substr($value, 0 , 4).'****'.substr($value, -4);
        }else{
            return '';
        }
    }
    /**
     * 保护期守卫
     * 如果在保护期返回true 不在保护期返回false
     * @param  [type] $value [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    public static function getGuardStateAttr($value, $data)
    {
        //开启 用户保护器
        if (CUSTOMER_BIND_SWITCH && !empty($data['BussinessId']) && $data['BussinessId']!==Pub::userid()&&!Rolepower::ispower(204007)) {
            $data = Customer::where('CompanyId',$data['CompanyId'])->find();
            if(!empty($data) && $data->guard_state==true){
                //在保护期
                return true;
            }
        }
        return false;
    }



    /**
     * 获取信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function user_getinfo($cid='',$userid = '',$hidden=['ReInfo'],$visible=[]){
       
        if(!empty($cid)){
            $data = Company::where('CompanyId',$cid)->find();
        }else{
            if(empty($userid)){
                $userlogininfo = Pub::getuserid();
                $userid = $userlogininfo['msg'];
            }
            $data = Company::where('UserId',$userid)->find();
        }
        if(empty($data)){
            return false;
        }
        if(!empty($hidden)){
            $data->hidden($hidden);
        }
        if(!empty($visible)){
            $data->visible($visible);
        }
        //客户id
        $data['CustomerId'] = Customer::where('CompanyId',$cid)->value('CustomerId');
        
        //客户所属区域
        if(!empty($data['StreetId'])){
            $data['street'] = Street::getinfo($data['StreetId']);
        }

        return $data;
    }

    /**
     * 用户修改企业信息
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function user_reinfo($data,$type='hawa'){
        if($type=='hawa'){
            $company = self::user_getinfo();
        }else if($type=='buss'){
            $company = self::user_getinfo($data['id']);
        }

        $reinfo = empty($company->ReInfo)?'':$company->ReInfo."\n";
        
        $userinfo = User::getinfo();
        $reinfo = $reinfo .'【' .$userinfo->Name.'|'.$userinfo->UserId.'】在'.date('Y-m-d H:i',time()).'进行了信息调整：';
        $nreinfo = '';
        foreach ($data as $key => $value) {
            $sb = $company->getfiledname($key);
            if(empty($sb)){
                continue;
            }
            if($key=='isplanform'){
                $value = (int)$value;
            }
            if(!empty($value)&&$company->$sb !== $value){
                $nreinfo =  $nreinfo . '字段【'.$company->getfiledname($key,2).'】由【'.$company->$sb .'】修改为【' .$value.'】;'."\n";
                //输入来的参数名非字段名需要进行替换
                $company->$sb = $value;
            }
        }
        if(!empty($nreinfo)){
            $reinfo = $reinfo ."\n" . $nreinfo;
            $company->ReInfo = $reinfo;
            $company->save();
        }
    }

    /**
     * 获取订单列表
     * @param  [type] $data    [主数据]
     * @param  string $type    [查询类型/hawa/buss]
     * @param  [type] $is_page [是否分页显示]
     * @return [type]          [description]
     */
    public static function usergetlist($data,$type = 'buss',$is_page = true){
        $rdata = Company::where('State','<>',Company::STATEDELETE);
        $userinfo = User::getinfo();

        if($type=='buss'){
            $rdata = Company::where('State',Company::STATEOK);
            $visible = ['CompanyId','UserName','Name','Img','Lon','Lat','Address','State','UserId','IsPlanform'];
            if(!empty($data['field'])){
                $visible = array_merge($data['field'],$visible);
            }
        }else if($type=='mana'){
            $rdata = Company::where('State',Company::STATEOK);
            $rdata = $rdata->with(['continfo']);
            $visible = ['CompanyId','UserName','CreateTime','UserTel','IsPlanform','Name','Img','State','Lon','Lat','Address'];
            if(!empty($data['field'])){
                $visible = array_merge($data['field'],$visible);
            }
        }else if($type=='regulatory'){
            $rdata = Company::where('State',Company::STATEOK);
            $rdata = $rdata->with(['continfo','orderinfo']);
            $visible = ['CompanyId','UserName','CreateTime','UserTel','IsPlanform','Name','Img','State','Lon','Lat','Address'];
            if(!empty($data['field'])){
                $visible = array_merge($data['field'],$visible);
            }
        }else{
            return moerr('缺少参数');
        }

        $option = come_model_option($data,$rdata,$is_page);
        
        $rdata = $option['rdata'];
        $data = $option['data'];
        
        if(!empty($data['field'])){
            $rdata = $rdata->field($visible);
        }
        if($type=='mana' || $type=='regulatory'){
            if(!empty($data['visible'])){
                $visible = array_merge($data['continfo'],$visible);
            }
        }

        $rdata = $rdata->select();

        if(empty($data['field'])){
            $rdata =  $rdata->visible($visible);
        }

        $ndata['list'] = $rdata->toArray();
        $ndata['statetext'] = Company::getStatusText();
        // $goodid = get_array_id($ndata,'GoodId','list','listinfo');
        if($is_page){
            $ndata['pageinfo'] = ['pageindex'=>$data['pageindex'],'pagemax'=>$data['count']];
        }
        return $ndata;
    }

    public static function getfiledname($str,$type=1){
        $file = ['isplanform'=>'IsPlanform','tel'=>'Tel',
                 'name'=>'Name','license'=>'License','img'=>'Img',
                 'lon'=>'Lon','lat'=>'Lat','address'=>'Address',
                 'usercard'=>'UserCard','username'=>'UserName',
                 'usertel'=>'UserTel','LicenseNumber'=>'LicenseNumber','StreetId'=>'StreetId'];
        $filename = ['isplanform'=>'是否有平台','tel'=>'企业电话',
                 'name'=>'公司名称','license'=>'营业执照','img'=>'企业大门照片',
                 'lon'=>'精度','lat'=>'维度','address'=>'地址',
                 'usercard'=>'专员身份证号','username'=>'专员姓名',
                 'usertel'=>'专员联系方式','LicenseNumber'=>'统一识别码','StreetId'=>'所属街道id'];
        if($type==1){
            if(empty($file[$str])){
                return false;
            }
            return $file[$str];
        }else{
            if(empty($filename[$str])){
                return false;
            }
            return $filename[$str];
        }
    }

}